package com.lcx.client;

import com.lcx.encoder.RpcDecoder;
import com.lcx.encoder.RpcEncoder;
import com.lcx.handler.UserClientHandler;
import com.lcx.request.RpcRequest;
import com.lcx.serializer.JSONSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.*;

/**
 * 消费端
 */
public class RPCConsumer{

    //1、创建一个线程池对象 --它要处理我们自定义事件
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器，UserClientHandler
    private static UserClientHandler userClientHandler;

    private static List<String> serviceList = new CopyOnWriteArrayList<>();

    //3.初始化客户端（创建连接池，设置boostrap，连接服务器）
    public static void init() throws InterruptedException {

        //获取持久节点下的临时节点
        String path = "/lcx-rpc/com.lcx.client.IUserService/provider";
        //创建连接
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .retryPolicy(new RetryNTimes(1, 1000))
                .connectionTimeoutMs(5000)
                .sessionTimeoutMs(5000).build();
        curatorFramework.start();
        try {
            //监听服务端
            PathChildrenCache cache = new PathChildrenCache(curatorFramework,path,true);
            cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
            cache.getListenable().addListener(new PathChildrenCacheListener() {
                @Override
                public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                    switch (event.getType()) {
                        //新增
                        case CHILD_ADDED:
                            String path = event.getData().getPath();
                            System.out.println("重启服务端，新增临时节点 : "+ event.getData().getPath() +"  数据:"+ new String(event.getData().getData()));
                            int index = path.lastIndexOf("/");
                            String str = path.substring(index + 1);
                            connect(str);
                            cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
                            break;
                        //删除
                        case CHILD_REMOVED:
                            System.out.println("关闭服务端，删除临时节点 : "+ event.getData().getPath() +"  数据:"+ new String(event.getData().getData()));
                            break;
                        //更新
                        case CHILD_UPDATED:
                            System.out.println("=====> CHILD_UPDATED : "+ event.getData().getPath() +"  数据:"+ new String(event.getData().getData()));
                            cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
                            break;
                        default:
                            break;
                    }
                }
            });
            // 第一次为空，需要从zk获取，后续通过watcher机制更新
            if (CollectionUtils.isEmpty(serviceList)) {
                System.out.println("首次从注册中心查找服务地址...");
                serviceList = curatorFramework.getChildren().forPath(path);
            }
            for (String s : serviceList) {
                connect(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void connect(String s) throws InterruptedException {
        String[] split = s.split(":");

        //1)初始化userClientHandler
        userClientHandler = new UserClientHandler();
        //2)创建连接池对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap = new Bootstrap();
        //4)配置启动引导对象
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new IdleStateHandler(0, 0, 3, TimeUnit.SECONDS));
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        //5）连接服务器
        bootstrap.connect(split[0],Integer.valueOf(split[1])).sync();
    }

    //4、使用jdk动态代理创建对象
    //serviceClass 根据接口生成子类代理对象， providerParam ： “UserService#sayHello”
    public static Object createProxy(Class<?> serviceClass,RpcRequest re){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1)初始化客户端client
                        if (userClientHandler == null){
                            init();
                        }
                        //设置参数
                        re.setClassName(method.getDeclaringClass().getName());
                        re.setMethodName(method.getName());
                        re.setParameters(args);
                        re.setParameterTypes(method.getParameterTypes());
                        //2)给UserClientHandler设置参数
                        //userClientHandler.setParam(providerParam+args[0]);
                        userClientHandler.setRequest(re);
                        //3)使用线程池开启一个线程处理call()写操作，返回结果
                        Object result = executorService.submit(userClientHandler).get();
                        return result;
                    }
                });
    }
}
